<template>
  <el-dialog 
    :model-value="modelValue"
    :title="isEdit ? '编辑租户' : '创建租户'"
    width="600px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:modelValue', $event)"
    @close="resetForm"
  >
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
    >
      <el-form-item label="租户ID" prop="tenantId">
        <el-input 
          v-model="form.tenantId" 
          :disabled="isEdit"
          placeholder="请输入租户ID（2-64位字符）"
          maxlength="64"
          show-word-limit
        />
        <div class="form-tip">租户ID创建后不可修改，只能包含字母、数字、下划线、连字符</div>
      </el-form-item>

      <el-form-item label="租户名称" prop="tenantName">
        <el-input 
          v-model="form.tenantName" 
          placeholder="请输入租户名称"
          maxlength="128"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="租户类型" prop="tenantType">
        <el-select 
          v-model="form.tenantType" 
          placeholder="请选择租户类型"
          style="width: 100%"
        >
          <el-option label="企业版" value="ENTERPRISE">
            <span>企业版</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 12px">
              高级功能，无限用户
            </span>
          </el-option>
          <el-option label="标准版" value="STANDARD">
            <span>标准版</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 12px">
              基础功能，限制用户数
            </span>
          </el-option>
          <el-option label="试用版" value="TRIAL">
            <span>试用版</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 12px">
              功能试用，有时间限制
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="最大用户数" prop="maxUsers">
        <el-input-number 
          v-model="form.maxUsers" 
          :min="1" 
          :max="100000"
          placeholder="不填写表示无限制"
          style="width: 100%"
          controls-position="right"
        />
        <div class="form-tip">留空表示无限制用户数量</div>
      </el-form-item>

      <el-form-item label="过期时间">
        <el-date-picker
          v-model="form.expireTime"
          type="datetime"
          placeholder="选择过期时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
          :disabled-date="disabledDate"
        />
        <div class="form-tip">留空表示永不过期</div>
      </el-form-item>

      <el-divider content-position="left">联系信息</el-divider>

      <el-form-item label="联系人姓名">
        <el-input 
          v-model="form.contactName" 
          placeholder="请输入联系人姓名" 
          maxlength="64"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input 
          v-model="form.contactPhone" 
          placeholder="请输入联系电话" 
          maxlength="11"
        />
      </el-form-item>

      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input 
          v-model="form.contactEmail" 
          placeholder="请输入联系邮箱" 
          maxlength="128"
        />
      </el-form-item>

      <el-form-item label="租户描述">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="3"
          placeholder="请输入租户描述"
          maxlength="512"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="$emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitting">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { tenantApi } from '@/api/tenant'
import type { TenantDTO } from '@/types/api'
import type { FormInstance, FormRules } from 'element-plus'

// Props & Emits
interface Props {
  modelValue: boolean
  tenant?: TenantDTO | null
}

const props = withDefaults(defineProps<Props>(), {
  tenant: null,
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const isEdit = computed(() => !!props.tenant?.id)

const form = reactive({
  tenantId: '',
  tenantName: '',
  tenantType: 'STANDARD',
  maxUsers: null as number | null,
  expireTime: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  description: '',
})

// 表单验证规则
const rules: FormRules = {
  tenantId: [
    { required: true, message: '请输入租户ID', trigger: 'blur' },
    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9_-]+$/, 
      message: '只能包含字母、数字、下划线和连字符', 
      trigger: 'blur' 
    },
  ],
  tenantName: [
    { required: true, message: '请输入租户名称', trigger: 'blur' },
    { min: 2, max: 128, message: '长度在 2 到 128 个字符', trigger: 'blur' },
  ],
  tenantType: [
    { required: true, message: '请选择租户类型', trigger: 'change' },
  ],
  maxUsers: [
    { 
      validator: (rule, value, callback) => {
        if (value !== null && value !== undefined && value <= 0) {
          callback(new Error('用户数量必须大于0'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    },
  ],
  contactPhone: [
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号码', 
      trigger: 'blur' 
    },
  ],
  contactEmail: [
    { 
      type: 'email', 
      message: '请输入正确的邮箱地址', 
      trigger: 'blur' 
    },
  ],
}

// 监听租户数据变化
watch(
  () => props.tenant,
  (tenant) => {
    if (tenant) {
      Object.assign(form, {
        tenantId: tenant.tenantId || '',
        tenantName: tenant.tenantName || '',
        tenantType: tenant.tenantType || 'STANDARD',
        maxUsers: tenant.maxUsers,
        expireTime: tenant.expireTime || '',
        contactName: tenant.contactName || '',
        contactPhone: tenant.contactPhone || '',
        contactEmail: tenant.contactEmail || '',
        description: tenant.description || '',
      })
    }
  },
  { immediate: true }
)

// 方法
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 准备提交数据
    const submitData: TenantDTO = {
      ...form,
      tenantType: form.tenantType as 'ENTERPRISE' | 'STANDARD' | 'TRIAL',
      maxUsers: form.maxUsers || undefined,
      expireTime: form.expireTime || undefined,
      contactName: form.contactName || undefined,
      contactPhone: form.contactPhone || undefined,
      contactEmail: form.contactEmail || undefined,
      description: form.description || undefined,
    }

    let response
    if (isEdit.value) {
      response = await tenantApi.updateTenant(form.tenantId, submitData)
    } else {
      response = await tenantApi.createTenant(submitData)
    }

    if (response.success) {
      ElMessage.success(isEdit.value ? '租户更新成功' : '租户创建成功')
      emit('update:modelValue', false)
      emit('success')
    } else {
      ElMessage.error(response.message || (isEdit.value ? '租户更新失败' : '租户创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    // 表单验证失败时不显示错误消息
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    tenantId: '',
    tenantName: '',
    tenantType: 'STANDARD',
    maxUsers: null,
    expireTime: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    description: '',
  })
}

// 禁用过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
  line-height: 1.4;
}

:deep(.el-divider__text) {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
